﻿using WebApplication1.Infrastructure.DatabaseContext;
using System.Linq.Expressions;
using WebApplication1.Core.Domain.Entities;
using WebApplication1.Core.Domain.RepositoryContracts;
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Infrastructure.Repositories {
    public class LouYuanRepository : ILouYuanRepository {

        private readonly SQLiteDbContext _db;

        public LouYuanRepository(SQLiteDbContext dbContext) {
            _db = dbContext;
        }

        public async Task<LouYuan> AddLouYuan(LouYuan LouYuan) {
            await _db.LouYuan.AddAsync(LouYuan);
            await _db.SaveChangesAsync();
            return LouYuan;
        }

        public async Task<bool> DeleteLouYuan(ushort LouYuanID) {
            _db.LouYuan.RemoveRange(_db.LouYuan.Where(temp => temp.LouYuanID == LouYuanID));
            int rowChanged = await _db.SaveChangesAsync();
            return rowChanged > 0;
        }

        public async Task<IEnumerable<LouYuan>> GetAllLouYuan() {
            return await _db.LouYuan.ToListAsync();//导航属性的状态在默认情况下不会自动去还原的，及为null，Include扩展方法的意思就是加载导航属性中的内容，它会自动还原状态
        }

        public async Task<IEnumerable<LouYuan>> GetFilteredLouYuan(Expression<Func<LouYuan, bool>> expression) {
            return await _db.LouYuan.Where(expression).ToListAsync();
        }

        public async Task<LouYuan?> GetLouYuanByLouYuanID(ushort LouYuanID) {
            return await _db.LouYuan.FirstOrDefaultAsync(temp => temp.LouYuanID == LouYuanID);
        }

        public async Task<bool> UpdateLouYuan(LouYuan LouYuan) {
            LouYuan? matched = await _db.LouYuan.FirstOrDefaultAsync(temp => temp.LouYuanID == LouYuan.LouYuanID);
            if(matched == null) { return false; }
            matched.MingCheng = LouYuan.MingCheng;
            matched.FangWuShuLiang = LouYuan.FangWuShuLiang;
            matched.DongShu = LouYuan.DongShu;
            matched.JianZhuMianJi = LouYuan.JianZhuMianJi;
            matched.JianChengShiJian = LouYuan.JianChengShiJian;
            matched.SheQuID = LouYuan.SheQuID;
            matched.DiZhi = LouYuan.DiZhi;
            await _db.SaveChangesAsync();
            return true;
        }
    }
}
